// 引入模块
const express = require('express');
// 开启路由
const r = express.Router();
//  链接数据库
const pool = require('../pool.js');

// 测试链接
r.get('/cs',(req,res)=>{
	res.send('ajax服务器成功开启')
});

// 用户注册
r.post("/v1/reg",(req,res)=>{
	var obj = req.body;
	sql = 'insert into xz_user set ?'
	pool.query(sql,[obj],(err,result)=>{
		if(err) throw err;
		if(result.affectedRows===0){
			res.send("0");
		}else{
			res.send("1");
		}
	});
});

// 用户登录
r.get("/v1/login/:uname&:upwd",(req,res)=>{
	var $uname = req.params.uname;
	var $upwd = req.params.upwd;

	sql = "select * from xz_user where uname=? and upwd=?"
	pool.query(sql, [$uname, $upwd], (err, result)=>{
		if(err) throw err;
		if(result.length > 0){ res.send("1"); }
		    else{ res.send("0"); }
	});
});

// 获取用户分页列表
r.get("/v1/list/:page&:count",(req,res)=>{
	var $page = req.params.page;
	var $count = req.params.count;
	$page = parseInt(($page));
	$count = parseInt(($count));
	
	sql = "select * from xz_user limit ?,?"
	pool.query(sql,[$page,$count],(err,result)=>{
		if(err) throw err;
		if(result.length>0){
			res.send(result);
		}else{
			res.send("0");
		}
	});
});

// 根据uid删除
r.delete("/v1/del/:uid",(req,res)=>{
	var $uid = req.params.uid;
	
	sql = "delete from xz_user where uid=?"
	pool.query(sql,[$uid],(err,result)=>{
		if(err) throw err;
		if(result.affectedRows===0){
			res.send("0");
		}else{
			res.send("1");
		}
	});
});

// 根据uid查询用户
r.get("/v1/search/:uid",(req,res)=>{
	var $uid = req.params.uid;

	sql = "select * from xz_user where uid=?"
	pool.query(sql,[$uid],(err,result)=>{
		if(err) throw err;
		if(result.length>0){
			res.send(result);
		}else{
			res.send("0");
		}
	});
});

// 根据uid修改用户
r.put("/v1/update",(req,res)=>{
     var obj = req.body;
	console.log(req.body);
	sql = 'UPDATE xz_user SET ? WHERE uid = ?';
	pool.query(sql,[obj,obj.uid],(err,result)=>{
		if(err) throw err;
		if(result.affectedRows===0){
			res.send("0");
		}else{
			res.send("1");
		}
	});
});

// 检测手机
r.get("/v1/checkphone/:phone",(req,res)=>{
	var $phone = req.params.phone;

	sql = "select phone from xz_user where phone=?"
	pool.query(sql, [$phone],(err,result)=>{
		if(err) throw err;
		if(result.length > 0){ res.send("1"); }
		    else{ res.send("0"); }
	});
});

// 检测用户名
r.get("/v1/checkuname/:uname",(req,res)=>{
	var $phone = req.params.uname;

	sql = "select uname from xz_user where uname=?"
	pool.query(sql, [$uname],(err,result)=>{
		if(err) throw err;
		if(result.length > 0){ res.send("1"); }
		    else{ res.send("0"); }
	});
});

// 检测邮箱
r.get("/v1/checkemail/:email",(req,res)=>{
	var $email = req.params.email;

	sql = "select email from xz_user where email=?"
	pool.query(sql, [$email],(err,result)=>{
		if(err) throw err;
		if(result.length > 0){ res.send("1"); }
		    else{ res.send("0"); }
	});
});















// 文件最后导出路由
module.exports = r;
